﻿<%@ WebHandler Language="C#" Class="RbRectifyMeasuresManageHandler" %>

/*Description: 热表整改措施管理
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20250408
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Collections;
using NPOI.SS.UserModel;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using BusinessRule.Common;

public class RbRectifyMeasuresManageHandler : IHttpHandler
{

    string rbFactoryID = System.Configuration.ConfigurationManager.AppSettings["RBFactoryID"].ToString(); //热表ID
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string action = context.Request["action"].ToString();
            switch (action)
            {
                case "GetRectifyMeasuresList": //获取整改措施数据列表
                    GetRectifyMeasuresList(context);
                    break;
                case "SaveContainerCheckRectifyMeasures": //保存检验的整改措施
                    SaveContainerCheckRectifyMeasures(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未知功能" }));
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 获取整改措施数据列表
    /// </summary>
    /// <param name="context"></param>
    private void GetRectifyMeasuresList(HttpContext context)
    {
        Dictionary<string, string> dicParam = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["paramData"].ToString());
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT c.mfgordername,c.productname,c.containername,ws.workflowstepname,s.stepno,s.description stepname,
                            cci.lossqty,cci.reworkqty,cci.rectifymeasures,cci.containercheckinfoid
                            FROM containercheckinfo2 cci 
                            LEFT JOIN containercurrentinfo c ON c.containerid = cci.containerid
                            LEFT JOIN workflowstep ws ON ws.workflowstepid = cci.workflowstepid
                            LEFT JOIN stepinfo s ON s.stepinfoid = cci.stepinfoid
                            WHERE ((cci.lossreason = '责任报废' AND NVL(cci.lossqty, 0) != 0) OR NVL(cci.reworkqty, 0) != 0) AND cci.isuse = 0 
                            AND c.containerstatus = 1 AND c.originalfactoryid = '{0}'
                            ", rbFactoryID);
        if (dicParam.ContainsKey("mfgOrderName") && !string.IsNullOrWhiteSpace(dicParam["mfgOrderName"])) //查询订单号
        {
            sql.AppendFormat(" AND c.mfgordername LIKE '%{0}%'", dicParam["mfgOrderName"]);
        }
        if (dicParam.ContainsKey("containerName") && !string.IsNullOrWhiteSpace(dicParam["containerName"]))//查询批次号
        {
            sql.AppendFormat(" AND c.containername LIKE '%{0}%'", dicParam["containerName"]);
        }
        if (dicParam.ContainsKey("productName") && !string.IsNullOrWhiteSpace(dicParam["productName"]))//查询件号
        {
            sql.AppendFormat(" AND c.productname LIKE '%{0}%'", dicParam["productName"]);
        }
        sql.AppendLine(" ORDER BY c.containerid,s.stepseq");
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(dicParam["pageIndex"]);
        pageDto.PageSize = int.Parse(dicParam["pageSize"]);
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存检验的整改措施
    /// </summary>
    /// <param name="context"></param>
    private void SaveContainerCheckRectifyMeasures(HttpContext context)
    {
        uMESProcessResult res = new uMESProcessResult();
        /*百分比数据必填*/
        string measures = context.Request["measures"].ToString();
        if (string.IsNullOrWhiteSpace(measures))
        {
            res.Result = false; res.Message = "请选择整改百分比！";
            context.Response.Write(JsonConvert.SerializeObject(res));
            return;
        }
        /*验证百分比数据，必须和前端下拉框数据保持一致*/
        List<int> measuresList = new List<int>() { 25, 50, 75, 100 };
        if (!measuresList.Contains(int.Parse(measures.TrimEnd('%'))))
        {
            res.Result = false; res.Message = "百分比数值或者格式错误！";
            context.Response.Write(JsonConvert.SerializeObject(res));
            return;
        }
        /*检验数据必须勾选*/
        DataTable dtCheck = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        if (dtCheck.Rows.Count == 0)
        {
            res.Result = false; res.Message = "请选择数据！";
            context.Response.Write(JsonConvert.SerializeObject(res));
            return;
        }
        /*循环将整改百分比保存到每个检验中去*/
        List<ExcuteEntity> entityList = new List<ExcuteEntity>();
        foreach (DataRow item in dtCheck.Rows)
        {
            ExcuteEntity exuteEntity = new ExcuteEntity("containercheckinfo2", ExcuteEntity.ExcuteTypeEnum.update);
            exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("containercheckinfoid", item["containercheckinfoid"].ToString(), FieldEntity.FieldTypeEnum.Str) };
            List<FieldEntity> excuteFieldList = new List<FieldEntity>();
            excuteFieldList.Add(new FieldEntity("rectifymeasures", measures, FieldEntity.FieldTypeEnum.Str));
            exuteEntity.ExcuteFileds = excuteFieldList;
            entityList.Add(exuteEntity);
        }
        DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(entityList);
        res.Result = true; res.Message = "保存成功！";
        context.Response.Write(JsonConvert.SerializeObject(res));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}